<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermissionFn(1,'0')">添加权限</el-button>
        </div>
        <!-- row-key="id" 必须加 -->
        <el-table row-key="id" border :data="permissionList">
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="code" label="标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button v-if="scope.row.type===1" type="text" @click="addPermissionFn(2,scope.row.id)">添加</el-button>
              <el-button type="text" @click="editPermissionFn(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="delPermissionFn(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog :title="isEdit ? '编辑权限点':'新增权限点'" :visible="showDialog" @close="btnCancel">
          <!-- 表单 -->
          <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width:90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="addOrEditPerFn">确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getPermissionList, addPermission, getPermissionDetail, updatePermission, delPermission } from '@/api/permission'

// 将普通数组，转为树形结构
import { listToTreeData } from '@/utils'
export default {
  name: 'Permission',
  data() {
    // 同级目录下，名字不可以相同
    const validName = (rule, value, callback) => {
      // 1.新增
      // 1.1找pid 相同的兄弟
      let existNameList = this.originList.filter(item => item.pid === this.formData.pid)
      // 2.编辑
      if (this.isEdit) {
        // 找到所有的兄弟节点，并且把自身排除
        existNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      // 同级兄弟的name组成的数组
      const brotherName = existNameList.map(item => item.name).includes(value)
      // 如果输入的value值存在，为true，抛出异常
      brotherName ? callback(new Error(`${value} 在同级目录中已存在`)) : callback()
    }
    const validCode = (rule, value, callback) => {
      //  1. 新增
      // 1.1 找到 所有的code
      let existCodeList = this.originList
      // 2. 编辑
      // 2.1 排除自己
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }
      // 将code提取出来，组成一个新数组  includes 进行比较
      existCodeList
        .map(item => item.code)
        .includes(value) ? callback(new Error(`权限标识 ${value} 已存在`)) : callback()
    }
    return {
      permissionList: [],
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [{ required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }],
        code: [{ required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }]
      },
      isEdit: false,
      originList: [] // 在做校验时需要用到的数据
    }
  },
  created() {
    this.getPermissionListFn()
  },
  methods: {
    // 点击删除
    async delPermissionFn(id) {
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果点击取消
      if (confirmRes === 'cancel') return this.$message('您取消了删除')
      // 点击确定删除
      const res = await delPermission(id)
      // 给用户提示
      this.$message.success(res.message)
      // 刷新页面
      this.getPermissionListFn()
    },
    // 点击编辑按钮，展示编辑弹框
    async editPermissionFn(id) {
      // 调接口。查询权限数据
      const res = await getPermissionDetail(id)
      // 数据回显
      this.formData = res.data
      // 显示弹框
      this.showDialog = true
      this.isEdit = true
    },
    // 点击确定按钮，添加权限
    addOrEditPerFn() {
      this.$refs.perForm.validate(async valid => {
        if (!valid) return
        if (!this.isEdit) {
          const res = await addPermission(this.formData)
          this.$message.success(res.message)
        } else {
          const res = await updatePermission(this.formData)
          this.$message.success(res.message)
        }

        this.showDialog = false
        this.getPermissionListFn()
      })
    },
    // 点击添加按钮，展示弹框
    // type 为 1 表示页面权限  type 为 2 表示按钮权限
    addPermissionFn(type, pid) {
      this.formData.type = type
      this.formData.pid = pid
      this.showDialog = true
      this.isEdit = false
    },
    // 点击取消，关闭弹框
    btnCancel() {
      // 重置表单数据
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      // 重置表单验证
      this.$refs.perForm.resetFields()
      // 关闭弹框
      this.showDialog = false
    },
    // 获取所有的权限列表
    async  getPermissionListFn() {
      const res = await getPermissionList()
      // console.log(res.data)
      this.originList = res.data.map(item => {
        return ({
          id: item.id,
          pid: item.pid,
          name: item.name.trim(),
          code: item.code
        })
      })
      this.permissionList = listToTreeData(res.data)
    }
  }
}
</script>

   <style lang="scss" scoped></style>

